package com.wzcl.app.service.impl;

import com.wzcl.app.dao.model.*;
import com.wzcl.app.dao.repository.*;
import com.wzcl.app.model.common.RVO;
import com.wzcl.app.service.EssayCourseStudyRecordService;
import com.wzcl.app.service.UserTaskQuizAnswerService;
import com.wzcl.app.utils.CollectionUtil;
import com.wzcl.app.utils.DateUtil;
import lombok.extern.log4j.Log4j2;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;
import java.util.List;

/**
 * @author beingven
 * @Description 用户答案验证
 * @createTime 2020年12月27日 10:59:00
 */
@Service
@Log4j2
public class UserTaskQuizAnswerServiceImpl implements UserTaskQuizAnswerService {
    @Resource
    private UserTaskQuizAnswerRepository userTaskQuizAnswerRepository;
    @Resource
    private CatalogTaskRepository catalogTaskRepository;
    @Resource
    private EssayCourseQuestionBankRepository essayCourseQuestionBankRepository;
    @Resource
    private TaskEvaluateScoreRepository taskEvaluateScoreRepository;
    @Resource
    private AppUserRepository appUserRepository;
    @Resource
    private CatalogEvaluateScoreRepository catalogEvaluateScoreRepository;
    @Resource
    private EssayCourseStudyRecordService essayCourseStudyRecordService;

    @Override
    @Transactional
    public RVO getStar(Integer taskId) {
        String phone = SecurityContextHolder.getContext().getAuthentication().getName();
        //判断当前的任务是否是拍照任务（如果是拍照任务直接给三星）
        if (catalogTaskRepository.findByTaskId(taskId).getTaskType() == 1){
            taskEvaluateScoreRepository.save(new TaskEvaluateScore(3, taskId, phone, 0, 0, 1d));
            return RVO.success("获取用户评分成功", 3);
        }
        // 获取当前任务的总题数
        String questionList = catalogTaskRepository.findByTaskId(taskId).getQuestionList();
        if (questionList == null){
            return RVO.error("当前任务下没有添加题库数据");
        }
        int size = CollectionUtil.getListFromString(questionList, ",").size();
        // 获取回答过的的题数(包含语音题和非语音题)
        List<UserTaskQuizAnswer> quizAnswerList = userTaskQuizAnswerRepository.getQuestionByAnswer(taskId, phone);
        if (quizAnswerList.size() == 0){
            return RVO.error("该用户未答题");
        }
        // 计算正确率
        Integer score = 0;
        Integer count = 0;
        Integer trueNumber = 0;
        for (int index = 0; index < quizAnswerList.size(); index++) {
            //分别判断每道题的得分(语音题)和非语音题的正确率
            Integer answerResult = quizAnswerList.get(index).getAnswerResult();
            //计算语音题总得分
            if (answerResult >= 0 && answerResult <= 3){
                score += answerResult;
                count++;
            }
            //计算非语音题正确题数
            if (answerResult == 5){
                trueNumber++;
            }
        }
        //语音题得分率
        Double audio = 0d;
        if(count != 0){
            audio = Double.valueOf(score) / Double.valueOf(count * 3);
        }

        //非语音题正确率
        Double notAudio = 0d;
        if (size-count > 0){
            notAudio = Double.valueOf(trueNumber) / Double.valueOf(size-count);
        }
        Double accuracy = (audio+notAudio) / 2;
        // 评分
        Integer star = 0;
        if (accuracy >= 0.9){
            star = 3;
        }else if (accuracy >= 0.7){
            star = 2;
        }else if(accuracy >= 0.5){
            star = 1;
        }
        // 保存用户本任务答题报告
        taskEvaluateScoreRepository.save(new TaskEvaluateScore(star, taskId, phone, trueNumber, size-trueNumber, accuracy));
        // 更新任务结束时间
        essayCourseStudyRecordService.updateStudyTask(DateUtil.getDateBySystemTime(System.currentTimeMillis()), phone, taskId);
        return RVO.success("获取用户评分成功", star);
    }

    @Override
    public RVO saveAnswer(List<UserTaskQuizAnswer> quizAnswers) {
        String phone = SecurityContextHolder.getContext().getAuthentication().getName();
        if (quizAnswers.size() > 0){
            for (int index = 0; index < quizAnswers.size(); index++) {
                quizAnswers.get(index).setPhone(phone);
            }
            List<UserTaskQuizAnswer> quizAnswerList = userTaskQuizAnswerRepository.saveAll(quizAnswers);
            return RVO.success("保存成功",quizAnswerList);
        }
        return RVO.success("数组不能为空");
    }

    @Override
    public EssayCourseQuestionBank retrieveUserAnswerQuestion(Integer taskId) {
        String phone = SecurityContextHolder.getContext().getAuthentication().getName();
        //查询任务中绑定的题库集合
        List<String> list = CollectionUtil.getListFromString(catalogTaskRepository.findByTaskId(taskId).getQuestionList(), ",");
        //答题进度精准定位
        for (int index = list.size()-1; index >= 0; index--) {
            //将任务中绑定的id对应的集合，从后往前去答题表中检索
            System.out.println(Integer.valueOf(list.get(index)));
            UserTaskQuizAnswer userTaskQuizAnswer = userTaskQuizAnswerRepository.findIdByQuestionIdAndTaskId(Integer.valueOf(list.get(index)), taskId, phone);
            if (userTaskQuizAnswer != null){
                return essayCourseQuestionBankRepository.findQuestionBankById(userTaskQuizAnswer.getQuestionBankId());
            }
        }
        return null;
    }

    @Override
    @Transactional
    public RVO resetTask(Integer taskId) {
        String phone = SecurityContextHolder.getContext().getAuthentication().getName();
        AppUser appUser = appUserRepository.findByPhone(phone);
        //删除答题记录
        userTaskQuizAnswerRepository.deleteByTaskId(taskId, phone);
        //删除任务完成记录
        taskEvaluateScoreRepository.deleteByTaskId(taskId, phone);
        //根据任务id查询章节
        EssayCourseCatalog catalog = catalogTaskRepository.findByTaskId(taskId).getEssayCourseCatalog();
        //判断章节是否存在学习记录（已经学习完成）
        if (catalogEvaluateScoreRepository.findEvaluateByCatalogId(catalog.getId(), appUser.getId()) != null){
            //删除章节完成记录
            CatalogEvaluateScore catalogEvaluateScore = catalogEvaluateScoreRepository.findEvaluateByCatalogId(catalog.getId(), appUser.getId());
            catalogEvaluateScoreRepository.deleteById(catalogEvaluateScore.getId());
        }
        return RVO.success("重置答题进度成功");
    }
}